package com.qiantu.phone.ui.activity;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.zxing.WriterException;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.RoomShareBean;
import com.qiantu.api.http.HttpBaseData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.utils.CodeUtils;
import com.qiantu.phone.utils.ScreenshotUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class  RoomSharePhotoActivity extends AppActivity {
    private IWXAPI mWxApi;
    private static final int EDIT_ROOM_CODE = 666;
    private String roomSerialNo;
    private BottomEditDialog mBottomEditDialog;

    private TextView tvShareName;
    private TextView tvNameShare;
    private TextView tvRoomName;
    private TextView tvRoomNameShare;
    private TextView tvShareTime;
    private TextView tvTimeShare;
    private ImageView imgQR;
    private ImageView ivQRShare;
    private RoomShareBean shareBean = new RoomShareBean();
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    private SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.sss");
    private XXPermissions xxPermissions;
    ConstraintLayout screenShotShareImg;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_room_share_photo;
    }

    @Override
    protected void initView() {
        mWxApi = WXAPIFactory.createWXAPI(this, "wx316a4d4cc94c0ba9", false);
        mWxApi.registerApp("wx316a4d4cc94c0ba9");
        if(xxPermissions == null){
            xxPermissions = XXPermissions.with(this);
        }
        imgQR = findViewById(R.id.iv_qr_code);
        tvShareName = findViewById(R.id.tv_share_name);
        tvNameShare = findViewById(R.id.qr_code_share_name_share);
        tvRoomName = findViewById(R.id.tv_room_name);
        tvRoomNameShare = findViewById(R.id.qr_code_stay_room_share);
        tvShareTime = findViewById(R.id.tv_share_time);
        tvTimeShare = findViewById(R.id.qr_code_share_time_share);
        screenShotShareImg = findViewById(R.id.screen_shot_share_img);
        ivQRShare = findViewById(R.id.iv_qr_code_share);
//        initViewPager();
        setOnClickListener(R.id.iv_back,R.id.btn_save_photo, R.id.btn_share_wechat, R.id.btn_finish);
    }


    @Override
    protected void initData() {
        roomSerialNo = getString("roomSerialNo");
        shareBean = getSerializable("data");
        RoomBean roomBean = LLRoomDBManager.getInstance(this).getRoomByRoomSerialNo(roomSerialNo);
        tvShareName.setText(shareBean.getName());
        tvNameShare.setText(shareBean.getName());
        tvRoomName.setText(roomBean.getRoomName());
        tvRoomNameShare.setText(roomBean.getRoomName());
        try {
            Date fromTime = simpleDateFormat1.parse(shareBean.getFromTime());
            Date toTime = simpleDateFormat1.parse(shareBean.getToTime());
            tvShareTime.setText("从   "+simpleDateFormat.format(fromTime) + "\n至   " + simpleDateFormat.format(toTime));
            tvTimeShare.setText("从   "+simpleDateFormat.format(fromTime) + "\n至   " + simpleDateFormat.format(toTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String url = "";
        String ip = "";
        String ws = "";
        if(HttpBaseData.getInstance().isLocalService()){
            String[] urls = HttpBaseData.getInstance().getLocalServiceUrl().split(":");
            url = "http://" + urls[0] + ":30185";
            ip = "http://" + HttpBaseData.getInstance().getLocalServiceUrl() + "/api";
            ws = "http://" + HttpBaseData.getInstance().getLocalServiceWs() + "/hubs/linglu";
        }else{
            url = shareBean.getShareUrl();
        }
        createQRCode(url + "/?authCode=" + shareBean.getAuthCode() + "&cloudIp=" + ip + "&cloudWsIp=" + ws);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_save_photo:
                checkPermission();
                break;
            case R.id.btn_share_wechat:
                showWeChat();
                break;
            case R.id.btn_finish:
                finish();
                ActivityManager.getInstance().finishActivity(RoomShareInfoActivity.class);
                break;
        }
    }

    private void createQRCode(String url) {
        Bitmap bm = null;
        try {
            bm = CodeUtils.createCode(this, url,CodeUtils.dp2px(this, 200),
                    CodeUtils.dp2px(this, 200));
            imgQR.setImageBitmap(bm);
            ivQRShare.setImageBitmap(bm);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    private void showWeChat() {
        String url = "";
        String ip = "";
        String ws = "";
        if(HttpBaseData.getInstance().isLocalService()){
            url = "http://" + HttpBaseData.getInstance().getLocalServiceUrl() + ":30185";
            ip = HttpBaseData.getInstance().getLocalServiceUrl();
            ws = HttpBaseData.getInstance().getLocalServiceWs();
        }else{
            url = shareBean.getShareUrl();
        }
        weChatShare(url + "/?authCode=" + shareBean.getAuthCode() + "&cloudIp=" + ip + "&cloudWsIp=" + ws);
    }

    private void checkPermission(){
        xxPermissions.permission( Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            saveQRCodeToCream();
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
    }

    private void saveQRCodeToCream() {
        ScreenshotUtil.getBitmapByView(this,screenShotShareImg);
    }

    private void weChatShare(String webUrl) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.img_aboutapp);
        msg.setThumbImage(thumb);
        msg.title = "房间分享";
        String descriptionStr = "点击该链接，开启您的智慧之旅吧！";
        msg.description = descriptionStr;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        mWxApi.sendReq(req);
    }

}
